package com.lvliucun.validate.check.impl;

import com.alibaba.fastjson.JSONObject;
import com.lvliucun.validate.check.ParamChecker;
import com.lvliucun.validate.exception.CustomerErrorCodeEnum;
import com.lvliucun.validate.exception.ParamException;
import com.lvliucun.validate.utils.FiledNameSplitUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @version 1.0
 * @Description 参数校验器：字段绑定关系非空。A字段非空时B字段必须非空，A字段为空时，B字段可以为空。例如：A&B:BindNotNull
 * @Author:zhuojiajin
 * @Date 2020/8/15
 **/
@Component
public class ParamBindNotNull implements ParamChecker {

    @Override
    public boolean checkParam(JSONObject args, String filedName,String path) throws Exception {
        Boolean preFiled = true;
        if(filedName.contains("&")){
            String[] filedNames = filedName.split("&");
            if(filedNames.length == 2){
                String[] filedStr = FiledNameSplitUtil.getFileName(filedNames[0]);
                Map<String,Object> value = FiledNameSplitUtil.getFiledValue(filedStr,args);
                if(null == value || StringUtils.isEmpty(value.get("value"))){
                    preFiled = false;
                }
                filedStr = FiledNameSplitUtil.getFileName(filedNames[1]);
                value = FiledNameSplitUtil.getFiledValue(filedStr,args);
                if(null == value || StringUtils.isEmpty(value.get("value"))){
                    if(preFiled){
                        throw new ParamException(CustomerErrorCodeEnum.PARAM_NOT_NULL,filedStr[filedStr.length-1],path);
                    }
                }
            }else{
                throw new ParamException(CustomerErrorCodeEnum.PARAM_CHECKER_ILLEGAL,CustomerErrorCodeEnum.PARAM_CHECKER_ILLEGAL.getDescription(),path);
            }
        }else{
            throw new ParamException(CustomerErrorCodeEnum.PARAM_CHECKER_ILLEGAL,CustomerErrorCodeEnum.PARAM_CHECKER_ILLEGAL.getDescription(),path);
        }
        return true;
    }
}

